############################## 变量在随机森林模型中的重要性预测 #############################
##### 科研工具1  变量在随机森林模型中的重要性预测


library(forestplot)
library(ggplot2)
library(missRanger)
library(randomForest)
# 输入一些参数 获取随机深林影响结果的重要变量打分 
getwd()
setwd('父级路径')
agerange317dropna <- read.csv('source.csv')

agerange317dropna$allGroup <-as.factor(agerange317dropna$allGroup)
#urinary TNE2
agerange317dropna$urinaryTNE2 <- (agerange317dropna$URXCOTT /176.2151) +(agerange317dropna$URXHCTT /192.2145  )
#NNAL/TNE2
agerange317dropna$NNAL_TNE2 <- (agerange317dropna$URXNAL /agerange317dropna$urinaryTNE2)
#2-hydroxyfluorene (ng/L)
agerange317dropna$twohydroxyfluorene<- agerange317dropna$URXP04
#3-hydroxyfluorene (ng/L)
agerange317dropna$threehydroxyfluorene<- agerange317dropna$URXP03
#2-hydroxyfluorene/TNE2
agerange317dropna$twohydroxyfluorene_tne2<- agerange317dropna$twohydroxyfluorene /agerange317dropna$urinaryTNE2
#3-hydroxyfluorene/TNE2
agerange317dropna$threehydroxyfluorene_tne2<- agerange317dropna$threehydroxyfluorene /agerange317dropna$urinaryTNE2
# 2CyEMA (ng/mL)
agerange317dropna$twoCyEMA<- agerange317dropna$URXCYM
# 2CyEMA/TNE2
agerange317dropna$twoCyEMA_TNE2<- agerange317dropna$twoCyEMA /agerange317dropna$urinaryTNE2
colnames(agerange317dropna)

finalModel <- agerange317dropna[,c( 'smokersize','LBXCOT','LBXHCT','URXNAL','threehydroxyfluorene_tne2','urinaryTNE2',
                                    'twohydroxyfluorene_tne2','twoCyEMA_TNE2','NNAL_TNE2','twohydroxyfluorene','cartse','threehydroxyfluorene',
                                    'twoCyEMA','otherhomeTSE','otherindoorareaTSE','restaurantTSE','allGroup')]
# tryCatch({
#   alldataform
# })
# 
# 
# tryCatch({
#   missdataranger
# })

 finalModel <- missRanger(finalModel, pmm.k = 2, num.trees = 500)

set.seed(40)

finalModeltreeResult <- randomForest(allGroup ~ .,
                                     data = finalModel,
                                     ntree = 500,
                                     mtry = 16, # 自变量最大数
                                     importance = T)

# 随机森林重要变量保存
# 解决网站 为了保存重要变量生成图片地址 https://data-flair.training/blogs/random-forest-in-r/

important <- importance(finalModeltreeResult, type=2 )
Important_Features <- data.frame(Feature = row.names(important), Importance = important[, 1])

plot_<- ggplot(Important_Features,
               aes(x= reorder(Feature,Importance) , y = Importance) ) +
  geom_bar(stat = "identity",
           # fill = "#800086") +
           fill = "black") +
  coord_flip() +
  theme_light(base_size = 15) +
  xlab("Questionnaire and Biomarker Variables") +
  ylab("variable Importance score")+
  ggtitle("variable headTtile") +
  theme(plot.title = element_text(size=20))

ggsave("important_features.tiff", plot_)
